﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mckfrpc
{
    public partial class frps : Form
    {
        public frps()
        {
            InitializeComponent();
            // 在这里处理输出结果，例如显示在文本框中
            StartCmd();
        }

        private void StartCmd()
        {
            try
            {
                Thread t = new Thread(() =>
                {
                    Process proc = new Process();
                    proc.StartInfo.FileName = mck.frpc.Program.frpName;
                    //proc.StartInfo.Arguments = string.Format("10");//this is argument
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardInput = true; //标准输入
                    proc.StartInfo.RedirectStandardOutput = true; //标准输出
                    proc.StartInfo.CreateNoWindow = true;
                    proc.Start();
                    proc.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
                    proc.BeginOutputReadLine();
                    proc.WaitForExit();
                    proc.Close();

                });
                t.IsBackground = true;
                t.Start();
            }
            catch (Exception ex)
            {
                this.lsitBox_cmd.Items.Add(string.Format("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString()));
                MessageBox.Show("出错了，请查看运行日志！");
            }
        }

        private void OutputHandler(object sender, DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                string data = outLine.Data.ToString();
                byte[] bytes = Encoding.Default.GetBytes(data);
                data = System.Text.Encoding.GetEncoding("UTF-8").GetString(bytes);
                this.Invoke(
            new Action(() =>
            {
                this.lsitBox_cmd.Items.Add(data);
                this.lsitBox_cmd.SelectedIndex = lsitBox_cmd.Items.Count - 1;
                if (this.lsitBox_cmd.Items.Count > 1000)
                {
                    this.lsitBox_cmd.Items.Clear();
                }
            }));
            }
        }

        private void frps_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true; // 取消关闭窗体 

                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                this.frps_notifyIcon.Visible = true;
                //this.m_cartoonForm.CartoonClose();
                this.Hide();
                return;
            }
        }

        /// <summary>
        /// 关闭所有线程
        /// </summary>
        private void CloseProcess()
        {

            // 假设我们要结束的进程名为"notepad.exe"
            string processName = mck.frpc.Program.frpName;

            // 获取所有匹配的进程
            Process[] processes = Process.GetProcessesByName(processName);

            foreach (Process process in processes)
            {
                try
                {
                    // 确保有足够的权限
                    process.Kill(); // 结束进程
                    process.WaitForExit(); // 等待进程退出
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"无法结束进程: {ex.Message}");
                }
            }
        }

        private void frps_FormClosed(object sender, FormClosedEventArgs e)
        {
            //CloseProcess();
            //System.Environment.Exit(0);
        }

        /// <summary>
        /// 彻底退出app
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frps_toolStripMenuI_Click(object sender, EventArgs e)
        {
            CloseProcess();
            System.Environment.Exit(0);
        }

        private void frps_notifyIcon_DoubleClick(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.frps_notifyIcon.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }
    }
}
